package net.zkbc.helloworld.service.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import net.zkbc.helloworld.entity.User;
import net.zkbc.helloworld.mapper.UserMapper;
import net.zkbc.helloworld.service.UserService;

@Component
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;

	@Transactional(readOnly = true)
	@Override
	public User findUserByLoginName(String loginName) {
		if (StringUtils.isEmpty(loginName)) {
			return null;
		}

		return userMapper.findByLoginName(loginName);
	}

	@Transactional
	@Override
	public User saveUser(User user) {
		encodePassword(user);

		int result = userMapper.insert(user);
		if (result == 0) {
			return null;
		}

		return user;
	}

	private void encodePassword(User user) {
		if (StringUtils.isEmpty(user.getPlainPassword())) {
			return;
		}

		user.setLoginPasswordTime(new Date());
		user.setPassword(user.getPlainPassword());
	}

}
